package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.RequestProcessorImp;

import java.util.Date;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.msg.ExceptionResponse;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ModbusUtil;
import net.wimpi.modbus.msg.WriteMultipleCoilsRequest;
import net.wimpi.modbus.msg.WriteMultipleCoilsResponse;
import net.wimpi.modbus.procimg.DigitalOut;
import net.wimpi.modbus.procimg.IllegalAddressException;
import net.wimpi.modbus.procimg.SimpleDigitalOut;
import net.wimpi.modbus.util.BitVector;

public class WriteMultipleCoilsRequestProcessor extends AbstractRequestProcessor {

	private static final Integer INT_1 = new Integer(1);
	private static final Integer INT_0 = new Integer(0);

	@Override
	public ModbusResponse processRequest(ModbusRequest req) {
		
		ModbusResponse res;
		//TODO: chequear limites del protocolo
		BitVector bits = ((WriteMultipleCoilsRequest) req).getCoils();
		int baseDir = ((WriteMultipleCoilsRequest)req).getReference();
		int count = bits.size();
		Date date = new Date();
		
		res = new WriteMultipleCoilsResponse(baseDir, bits.size());
		
		try {
				
			for(int i = 0; i < count; i++){
				
				DigitalOut value = new SimpleDigitalOut(bits.getBit(i));
				int reference = baseDir + i;
				
				getImage().setDigitalOut(reference, value, date);
				
				if( getDeciveDAO() != null )
					if(value.isSet())
						getDeciveDAO().saveValue( getDevice(), reference ,INT_1 , AddressType.COIL );
					else
						getDeciveDAO().saveValue( getDevice(), reference ,INT_0 , AddressType.COIL );		
				
			}
		
			ModbusUtil.setFunctionCode(res, Modbus.WRITE_MULTIPLE_COILS);
		
		}
		catch(IllegalAddressException e){
			
			res = new ExceptionResponse(req.getFunctionCode(), 2);
			
		}
		
		ModbusUtil.setMessageData(res,req);
		
		return res;
		
	}

}
